﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Threading.Tasks;
using System.Diagnostics;
using Core;
using OrdersDAL.EntityModel;

namespace WinClient
{
    class Program
    {
        private static string _QueuePath;
        private static MessagingService _MessagingService;
        private static string _WinClientId;
        private static bool _KeepRunning = true;
 
        /// <summary>
        /// Win Client receiving Demand Alerts from Services
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            _WinClientId = Guid.NewGuid().ToString();
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Red;
            _QueuePath = Settings.Default.MSMQURL + 
                         string.Format("\\{0}_{1}",
                         MessagingService.ClientQueuePathPrefix, 
                         _WinClientId);

            _MessagingService = new MessagingService(_QueuePath);
            ReceiveDemandChangesAsync();
        }

  
        static void ReceiveDemandChangesAsync()
        {
            var acceptCancelKey = Task.Factory.StartNew(
                () => AcceptCancelAsync());

            Console.WriteLine("Win Client Started as {0}\r\nPress Esc to Cancel...", _WinClientId);

            while (_KeepRunning)
            {
                var task = Task.Factory.StartNew(() => _MessagingService.Receive<List<DemandCell>>());


                task.ContinueWith(
                    (t) =>
                    {
                        OnDemandChangesReceived(
                            t.Exception == null ? t.Result : null,
                            t.Id,
                            t.Exception
                        );
                    }
                );
            }
        }

        static void OnDemandChangesReceived(List<DemandCell> DemandCellList, int transid, Exception ex)
        {
            
            DemandCellList.ForEach(e => 
                Console.WriteLine(
                string.Format("Demand Changed For {0}, new value {1}",
                e.BarType,e.Change_Value)));
        }


        private static void AcceptCancelAsync()
        {
            var key = Console.ReadKey(true);
            while (key.Key != ConsoleKey.Escape)
            {
                key = Console.ReadKey(true);
            }
            _KeepRunning = false;
            ClientExit();
            Console.ReadKey();
        }

        static void ClientExit()
        {
            Console.WriteLine("Exiting....");
            _MessagingService.DeleteQueue();
        }

    }
}
